package com.wlcorp.forcazamis.dao.stock.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ibatis.dao.client.DaoException;
import com.wlcorp.forcazamis.dao.stock.IStockProductDAO;
import com.wlcorp.forcazamis.domain.stock.StockProduct;

public class StockProductDAOImpl extends HibernateDaoSupport implements IStockProductDAO {

	public void deleteStockProduct(StockProduct stockProduct)
			throws DaoException {
		stockProduct.setDeleteFlag(true);
		getHibernateTemplate().update(stockProduct);
	}

	public StockProduct getStockProductById(Long stockProductId)
			throws DaoException {
		return (StockProduct)getHibernateTemplate().get(StockProduct.class,stockProductId);
	}

	@SuppressWarnings("unchecked")
	public List getStockProductList(final StockProduct stockProduct)
			throws DaoException {
		final StringBuffer queryString = new StringBuffer("select stockProduct from StockProduct as stockProduct where 1=1 and stockProduct.deleteFlag=false");
		 
		return getHibernateTemplate().executeFind(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(queryString.toString());
				if(null != stockProduct && null != stockProduct.getMinRownum()){
					query.setFirstResult(stockProduct.getMinRownum());
					query.setMaxResults(stockProduct.getNumPerPage());
				}
				return query.list();
			}
		});
	}

	public void saveStockProduct(StockProduct stockProduct) throws DaoException {
		getHibernateTemplate().flush();
		getHibernateTemplate().clear();
		getHibernateTemplate().saveOrUpdate(stockProduct);		
	}
	
	public void updateStockProduct(StockProduct stockProduct) throws DaoException {
		getHibernateTemplate().update(stockProduct);		
	}

	@SuppressWarnings("unchecked")
	public List<StockProduct> getStockProductListByStockId(Long stockId) throws DaoException {
		StringBuffer queryString = new StringBuffer(
				"from StockProduct as stockProduct where stockProduct.deleteFlag=false and ")
				.append(" stockProduct.stock.stockId = ").append(stockId);
		return getHibernateTemplate().find(queryString.toString());
	}
	
	public Long getMaxStockProductId() throws DaoException {
		 String hql="select max(stockProduct.productId) from StockProduct stockProduct";
		 return ((Long)getHibernateTemplate().iterate(hql).next()).longValue();
	}
 
}
